<template>
  <el-dialog
    :visible.sync="visible"
    :title="$t('updatePassword.title')"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="600px"
    :append-to-body="true">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm"  label-width="120px">
       <input type="password" class="hide" id="loginPassword"/>
          <input type="text" class="hide" id="loginUserName"/>
      <el-form-item prop="mobile" :label="$t('user.mobile')">
        <el-input v-model="dataForm.mobile" autocomplate="new-password" size="small" :placeholder="$t('user.mobile')"></el-input>
        <el-input v-model="dataForm.mobile2" autocomplate="new-password" placeholder="请输入昵称" v-show="false"></el-input>
      </el-form-item>
      <el-form-item prop="newPassword" autocomplete="off" :label="$t('updatePassword.newPassword')">
        <el-input v-model="dataForm.newPassword2" autocomplate="new-password" size="small" type="password" placeholder="请输入昵称" v-show="false"></el-input>
        <el-input v-model="dataForm.newPassword" autocomplate="new-password" size="small" type="password" :placeholder="$t('updatePassword.newPassword')"></el-input>
      </el-form-item>
      <el-form-item prop="comfirmPassword" autocomplete="off" :label="$t('updatePassword.comfirmPassword')">
        <el-input v-model="dataForm.comfirmPassword" size="small" type="password" @change="checkpwd" :placeholder="$t('updatePassword.comfirmPassword')"></el-input>
      </el-form-item>
      <el-form-item prop="smsyzm" label="验证码">
        <el-input v-model="dataForm.smsyzm" style="width: 255px;margin-right: 15px;" size="small" placeholder="手机验证码">

        </el-input>
        <el-button  v-if="btnShow"  type="primary"  size="small"  @click="sendMsg" >发送短信</el-button>
        <el-button  v-else type="primary" style="width:80px;"  size="small"  disabled >{{count}} s</el-button>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from 'lodash/debounce'
import { isMobile } from '@/utils/validate'
import { clearLoginInfo, getUUID } from '@/utils'
export default {
  data () {
    return {
      visible: false,
      btnShow: true,
      count: '',
      timer: null,
      dataForm: {
        mobile2: '',
        newPassword2: '',
        mobile: '',
        smsyzm: '',
        uuid: '',
        password: '',
        newPassword: '',
        comfirmPassword: ''

      }
    }
  },
  computed: {
    dataRule () {
      var validateComfirmPassword = (rule, value, callback) => {
        if (this.dataForm.newPassword !== value) {
          return callback(new Error(this.$t('updatePassword.validate.comfirmPassword')))
        }
        callback()
      }
      var validateMobile = (rule, value, callback) => {
        if (!isMobile(value)) {
          return callback(new Error(this.$t('validate.format', { 'attr': this.$t('user.mobile') })))
        }
        callback()
      }
      return {
        mobile: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }
        ],
        smsyzm: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        password: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        comfirmPassword: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' },
          { validator: validateComfirmPassword, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    init () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
      })
    },
    getCode () {
      const TIME_COUNT = 60
      if (!this.timer) {
        this.count = TIME_COUNT
        this.btnShow = false
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--
          } else {
            this.btnShow = true
            clearInterval(this.timer)
            this.timer = null
          }
        }, 1000)
      }
    },

    sendMsg () {
      if (!this.dataForm.mobile) {
        this.$message.error('请先输入手机号')
        return false
      }
      this.getCode()
      this.dataForm.uuid = getUUID()
      this.$http.get(`${window.SITE_CONFIG['apiURL']}/smsyzm?uuid=${this.dataForm.uuid}&tel=${this.dataForm.mobile}`
      ).then(({ data: res }) => {
        return this.$message({
          message: res.data,
          type: 'success',
          duration: 500
        })
      }).catch(() => {
      })
    },
    checkpwd () {
      if (this.dataForm.newPassword.length < 1) {
        this.dataForm.newPassword = ''
        this.dataForm.comfirmPassword = ''
        return this.$message.error('新密码不能为空')
      } else if (this.dataForm.newPassword !== this.dataForm.comfirmPassword) {
        this.dataForm.newPassword = ''
        this.dataForm.comfirmPassword = ''
        return this.$message.error('两次密码不一致！')
      } else if (this.dataForm.newPassword.length < 8) {
        this.dataForm.newPassword = ''
        this.dataForm.comfirmPassword = ''
        return this.$message.error('用户登录密码必须在8位以上')
      } else {
        var value = this.dataForm.newPassword // 得到输入框中的值
        var pattern = /(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{8,})$/ // 创建正则表达式对象
        var flag = pattern.test(value) // 测试匹配

        if (!flag) { // 判断匹配
          this.dataForm.newPassword = ''
          this.dataForm.comfirmPassword = ''
          return this.$message.error('格式错误，请使用数字加字母的格式，请重新输入！')
        }
      }
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.$http.put('/sys/user/password', this.dataForm).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              clearLoginInfo()
              this.$router.replace({ name: 'login' })
            }
          })
        }).catch(() => {})
      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>
<style lang="scss">
  .el-form{
        padding: 0 20px;
  }
  .hide{
    width: 0;
    position: absolute;
    border: none;
  }
</style>
